import datetime
import logging
import os
import sys
from logging.handlers import TimedRotatingFileHandler


class Logger:
    __instance__ = None

    def __init__(self):
        if Logger.__instance__ is None:
            Logger.__create_instance__()

    @staticmethod
    def __create_instance__():

        logging.root.setLevel(logging.NOTSET)

        # 日志
        logger = logging.getLogger(__name__)

        logFmt = logging.Formatter('%(asctime)s - %(message)s')

        # 文件日志
        fileHandler = TimedRotatingFileHandler("..\\..\\logs\\sync.log", when="D", interval=1, backupCount=10,
                                               encoding="UTF-8", delay=False)
        fileHandler.setFormatter(logFmt)
        fileHandler.setLevel(logging.DEBUG)
        logger.addHandler(fileHandler)

        # 控制台
        consoleHandler = logging.StreamHandler(stream=sys.stdout)
        consoleHandler.setFormatter(logFmt)
        consoleHandler.setLevel(logging.DEBUG)
        logger.addHandler(consoleHandler)

        Logger.__instance__ = logger

    @staticmethod
    def __colorText__(text: str, color: str):
        """
        :param text: 文字
        :param color: 文字颜色 red,green,yellow,blue
        :return:
        """
        colorMap = {"red": "31", "green": "32", "yellow": "33", "blue": "34"}
        displayColor = colorMap[color] if color in colorMap.keys() else 37
        return "\033[0;%sm%s\033[0m" % (displayColor, text)

    @staticmethod
    def debug(s):
        Logger.__instance__.debug("debug - %s - %s" % (s, os.getpid()))

    def info(self, s):
        Logger.__instance__.info("%s - %s - %s" % (self.__colorText__("info", 'green'), os.getpid(), s))

    def warn(self, s):
        Logger.__instance__.warning("%s - %s - %s" % (self.__colorText__("warn", 'yellow'),  os.getpid(), s))

    def error(self, s, e=None):
        Logger.__instance__.error("%s - %s - %s" % (self.__colorText__("error", 'red'),  os.getpid(), s))
        if e is not None:
            Logger.__instance__.error("%s - %s - %s - %s" % (self.__colorText__("error", 'red'), e))

    def fatal(self, s, e=None):
        Logger.__instance__.fatal("%s - %s - %s" % (self.__colorText__("fatal", 'red'),  os.getpid(), s))
        if e is not None:
            Logger.__instance__.fatal("%s - %s - %s" % (self.__colorText__("error", 'red'), e))

    # 跑批进度计算

    def progress_bar(self, name, finish_tasks_number, tasks_number):
        """
        进度条

        :param finish_tasks_number: int, 已完成的任务数
        :param tasks_number: int, 总的任务数
        :return:
        """

        percentage = round(finish_tasks_number / tasks_number * 100)
        print("\r进度: {}%: ".format(percentage), "▓" * (percentage // 2), end="")
        sys.stdout.flush()
